package com.easy.interceptor;

import com.alibaba.fastjson.JSON;
import com.easy.util.LayData;
import com.easy.util.SYS;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Enumeration;

public class ShoppingLoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //检查是否有登陆状态
        HttpSession session = request.getSession();
        Object obj = session.getAttribute(SYS.SHOPPING_LOGIN_USER);
        if(obj!=null){
            return true;
        }else{
            //分支判断  请求方式  访问页面(shopping/页面名)  重定向
            //                    Ajax                   json
            //重定向
            String requestwith = request.getHeader("X-Requested-With");
            if("XMLHttpRequest".equals(requestwith)){
                //ajax
                LayData result=LayData.success(401,"您还未登录,请登录");
                String json = JSON.toJSONString(result);
                response.setHeader("Content-Type", "application/json");
                response.setCharacterEncoding("utf-8");
                response.getWriter().write(json);
            }else{
                String path=request.getContextPath();
                String basePath=request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
                response.sendRedirect(basePath+"shopping/login");
            }
            return false;
        }

    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
